package com.efounder.form.comp;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.efounder.action.IAction;
import com.efounder.action.IActionWidget;
import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.form.base.IComponent;
import com.efounder.form.builder.IScriptObject;
import com.efounder.form.util.FormCompUtil;
import com.efounder.frame.ViewSize;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.StringUtil;
import com.efounder.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import static com.efounder.form.util.FormCompUtil.getLayoutGravity;

/**
 * Created by Javor on 16/9/2.
 */

public class FormCardButton extends androidx.appcompat.widget.AppCompatButton implements IComponent, IScriptObject,
        IUIComponent, DataSetListener, IActionWidget {

    private Map scriptObject = new HashMap();
    private Map scriptContext = new HashMap();

    private String id;
    private int height;
    private int width;
    private int gap = 0;
    private String url;

    private ViewSize size = new ViewSize(0, 0);
    private int percentWidth;
    private int percentHeight;

    private int color;

    //是否可以点击
    private boolean clickEnable = true;

    //按下的颜色
    private int backgroundDownColor;
    //焦点的颜色
    private int foucsColor = getResources().getColor(R.color.title_Background);
    private int backgroundColor ;
    private String backgroundColorHex;
    //禁用时的颜色
    private int backgroundDisableColor;
    private String horizontalAlign;
    private String verticalAlign;

    private static final String DEFAULT_FONT_SIZE = "16";
    private static final int DEFAULT_BUTTON_RADIUS = 2;
    private String fontSize;
    private IUIComponent parentComp;
    private IAction action;
    private String label;


    public FormCardButton() {
        super(AppContext.getCurrentActivity());
        this.setTextColor(Color.rgb(255, 255, 255));
        // this.setBackgroundColor(Color.parseColor("#"+234422));
        setTextSize(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(DEFAULT_FONT_SIZE));
    }

    public FormCardButton(Context context) {
        super(context);
    }

    public FormCardButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
        this.setText(label);
    }


    @Override
    public String getID() {
        return id;
    }

    @Override
    public void setID(String id) {
        this.id = id;
    }

//    private ImageLoader imageLoader;

    @Override
    public void setLayout() {
        FormCompUtil.setLayoutSize(this);

        if (horizontalAlign == null) {
            horizontalAlign = "middle";
        }
        if (verticalAlign == null) {
            verticalAlign = "middle";
        }
        this.setGravity(getLayoutGravity(horizontalAlign, verticalAlign));
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void creationComplete() {

        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行脚本
                buttonClick();
            }
        });

        if (clickEnable) {
            if (backgroundColor == 0) {
                if (TextUtils.isEmpty(backgroundColorHex)) {
                    backgroundColor = getResources().getColor(R.color.title_Background);
                } else {
                    try {
                        if (!backgroundColorHex.startsWith("#")) {
                            backgroundColorHex = "#" + backgroundColorHex;
                        }
                        backgroundColor = Color.parseColor(backgroundColorHex);
                    } catch (Exception e) {

                    }
                }
            }
            GradientDrawable normal = getDrawable(DEFAULT_BUTTON_RADIUS, StringUtil.formColorToColor(backgroundColor), 1, StringUtil.formColorToColor(backgroundColor));
            GradientDrawable press = getDrawable(DEFAULT_BUTTON_RADIUS, StringUtil.formColorToColor(foucsColor), 1, StringUtil.formColorToColor(foucsColor));

            StateListDrawable selector = getSelector(normal, press);
            this.setBackgroundDrawable(selector);
        }

    }

    public void buttonClick() {
        //执行脚本
        try {
            FormAppUtil.executeCompScripts(FormCardButton.this, scriptContext, "click", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行action
        if (action != null) {
            try {
                this.action.doAction();
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(getContext(), "操作失败，请稍候再试");
            }
        } else {
            ToastUtil.showToast(getContext(), "没有绑定的action！");
        }

    }

    public String getHorizontalAlign() {
        return horizontalAlign;
    }

    public void setHorizontalAlign(String horizontalAlign) {
        this.horizontalAlign = horizontalAlign;
    }

    public String getVerticalAlign() {
        return verticalAlign;
    }

    public void setVerticalAlign(String verticalAlign) {
        this.verticalAlign = verticalAlign;
    }


    public String getFontSize() {
        return fontSize;
    }

    public void setFontSize(String fontSize) {
        this.fontSize = fontSize;
        if (fontSize == null || "0".equals(fontSize)) {
            fontSize = DEFAULT_FONT_SIZE;
        }
        try {
            if (fontSize.compareTo(DEFAULT_FONT_SIZE) < 0) {
                return;
            }
            setTextSize(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(fontSize));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;

//        imageLoader = ImageLoader.getInstance();
//        imageLoader.loadImage(url, new ImageLoadingListener() {
//            @Override
//            public void onLoadingStarted(String s, View view) {
//
//            }
//
//            @Override
//            public void onLoadingFailed(String s, View view, FailReason failReason) {
//
//            }
//
//            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
//            @Override
//            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//            }
//
//            @Override
//            public void onLoadingCancelled(String s, View view) {
//
//            }
//        });
    }


    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        if (color == 0) {
            color = getResources().getColor(R.color.white);
        }
        this.color = color;
        this.setTextColor(StringUtil.formColorToColor(color));
    }

    /**
     * 设置背景选择器
     *
     * @param pressedDraw
     * @param normalDraw
     * @return
     */
    private StateListDrawable getSelector(Drawable normalDraw, Drawable pressedDraw) {
        StateListDrawable stateListDrawable = new StateListDrawable();
//        stateListDrawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, pressedDraw);
//        stateListDrawable.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressedDraw);
//        stateListDrawable.addState(new int[]{android.R.attr.state_focused}, pressedDraw);
//        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDraw);
        stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, normalDraw);
        stateListDrawable.addState(new int[]{}, normalDraw);
        return stateListDrawable;
    }

    /**
     * 设置shape
     *
     * @param radius
     * @param fillColor
     * @param width
     * @param strokeColor
     * @return
     */
    private GradientDrawable getDrawable(int radius, int fillColor, int width, int strokeColor) {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadius(radius);
        gradientDrawable.setColor(fillColor);
        gradientDrawable.setStroke(width, strokeColor);
        return gradientDrawable;
    }

    public int getBackgroundUpColor() {
        return backgroundColor;
    }

    public void setBackgroundUpColor(int backgroundUpColor1) {
       // if (backgroundColor != 0) {
            this.backgroundColor = backgroundUpColor1;
       // }
    }

    public boolean isClickEnable() {
        return clickEnable;
    }

    public void setClickEnable(boolean clickEnable) {
        this.clickEnable = clickEnable;
    }

//    public int getBackgroundDisableColor() {
//        return backgroundDisableColor;
//    }
//
//    public void setBackgroundDisableColor(int backgroundDisableColor) {
//        this.backgroundDisableColor = backgroundDisableColor;
//    }

    public int getFoucsColor() {
        return foucsColor;
    }

    public void setFoucsColor(int foucsColor) {
        if (foucsColor != 0) {
            this.foucsColor = foucsColor;
        }
    }

    public int getBackgroundDownColor() {
        return backgroundDownColor;
    }

    public void setBackgroundDownColor(int backgroundDownColor) {
        this.backgroundDownColor = backgroundDownColor;
    }


    @Override
    public Map getScriptObject() {
        return scriptObject;
    }

    @Override
    public void setScriptObject(Map scriptObject) {
        this.scriptObject = scriptObject;
    }

    @Override
    public String getEventScript(String key) {
        return (String) scriptObject.get(key);
    }

    @Override
    public void setEventScript(String key, String script) {
        scriptObject.put(key, script);
    }

    @Override
    public Map getScriptContext() {
        return scriptContext;
    }

    @Override
    public void setScriptContext(Map context) {
        scriptContext = context;
    }

    @Override
    public int getGap() {
        return gap;
    }

    @Override
    public void setGap(int gap) {
        this.gap = gap;
    }

    @Override
    public void setCompWidth(int width) {
        this.width = width;
    }

    @Override
    public int getCompWidth() {
        return this.width;
    }

    @Override
    public void setCompHeight(int height) {
        this.height = height;
    }

    @Override
    public int getCompHeight() {
        return this.height;
    }

    @Override
    public int getPercentWidth() {
        return percentWidth;
    }

    @Override
    public void setPercentWidth(int percentW) {
        this.percentWidth = percentW;
    }

    @Override
    public int getPercentHeight() {
        return percentHeight;
    }

    @Override
    public void setPercentHeight(int percentH) {
        this.percentHeight = percentH;
    }

    @Override
    public ViewSize getViewSize() {
        return size;
    }

    @Override
    public void setViewSize(ViewSize size) {
        this.size = size;
    }

    @Override
    public IUIComponent getParentComp() {
        return parentComp;
    }

    @Override
    public void setParentComp(IUIComponent comp) {
        parentComp = comp;
    }

    @Override
    public void dataSetChanged(DataSetEvent dataSetEvent) {

    }

    @Override
    public IAction getAction() {
        return action;
    }

    @Override
    public void setAction(IAction action) {
        this.action = action;
    }

    @Override
    public boolean getEnabled() {
        return true;
    }

    public String getBackgroundColorHex() {
        return backgroundColorHex;
    }

    public void setBackgroundColorHex(String backgroundColorHex) {
        this.backgroundColorHex = backgroundColorHex;
    }
}
